<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="100px">

      <el-form-item label="总充值总额" style="margin-left: 30px;"  v-if="isAdmin">
        <div style="color: green; font-size: 20px">{{ rechargeBalancePrice }}元</div>
      </el-form-item>
      <el-form-item label="我的充值总额" style="margin-left: 30px"  v-if="isAdmin">
        <div style="color: green; font-size: 20px">{{ myBalancePrice }}元</div>
      </el-form-item>
      <el-form-item label="我的充值总额" style="margin-left: 30px"  v-if="!isAdmin">
        <div style="color: green; font-size: 20px">{{ myBalancePrice }}元</div>
      </el-form-item>

      <el-form-item label="商户名称" prop="merchantId" style="margin-left: 50px" v-if="isAdmin">
        <template #default="scope">
          <el-select filterable clearable v-model="queryParams.merchantName" size="small" style="width: 200px; margin-right: 10px" @change="merchantChange(queryParams.merchantName)">
            <el-option v-for="item in merchantArr" :key="item.account" :label="item.account" :value="item.account" />
          </el-select>
        </template>
      </el-form-item>

      <el-form-item label="审核状态" prop="state">
        <el-select v-model="queryParams.state" size="small" style="width: 190px; margin-right: 10px">
          <el-option v-for="item in stateOptions" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>


      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['business:merchantBalance:add']" >
          新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="merchantBalanceList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />

      <el-table-column label="图片" align="center" prop="img" width="150px" fixed class="el-image-viewer_wrapper">
        <template #default="scope">
          <el-image v-if="scope.row.img !== null"
              style="width: 100px; height: 100px"
              :key="scope.row.id"
              :src="scope.row.img"
              :preview-teleported="true"
              :preview-src-list="[scope.row.img]">
          </el-image>

          <span v-if="scope.row.img === null"></span>
        </template>
      </el-table-column>


      <el-table-column label="商户名称" align="center" prop="merchantName" />

      <el-table-column label="类型" align="center" prop="type">
        <template #default="scope">
          <span v-if="scope.row.type === 'in'">客户充值</span>
          <span v-if="scope.row.type === 'out'">订单支付</span>
          <span v-if="scope.row.type === 'freightOut'">运费支付</span>
          <span v-if="scope.row.type === 'backIn'">订单退款</span>
        </template>
      </el-table-column>

      <el-table-column label="充值金额" align="center" prop="amount" />
      <el-table-column label="审核状态" align="center" prop="state">
        <template #default="scope">
          <el-tag type="info" v-if="scope.row.state === 0">待审核</el-tag>
          <el-tag type="success" v-if="scope.row.state === 1">审核完成</el-tag>
          <el-tag type="warning" v-if="scope.row.state === 2" :title="scope.row.backReason" style="cursor: pointer;">审核驳回</el-tag>
        </template>
      </el-table-column>

      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="审核时间" align="center" prop="createTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.applyEndTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" @click="handleConfig(scope.row.id, 'pass')"
                      v-if="scope.row.state === 0 && isAdmin">审核通过</el-button>

          <el-button link type="primary" @click="handleOperate(scope.row.id, 'reject')"
                     v-if="scope.row.state === 0 && isAdmin">审核驳回</el-button>

          <el-button link type="primary" @click="handleDelete(scope.row)" >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改商户的余额记录对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="merchantBalanceRef" :model="form" :rules="rules" label-width="80px">

        <el-form-item label="商户名称" prop="merchantId" v-if="isAdmin">
          <template #default="scope">
            <el-select v-model="form.merchantName" size="small" style="width: 500px; margin-right: 10px" filterable clearable @change="brandChange(form.merchantName)">
              <el-option v-for="item in merchantArr" :key="item.account" :label="item.account" :value="item.account" />
            </el-select>
          </template>
        </el-form-item>


        <el-form-item label="充值金额" prop="amount">
          <el-input v-model="form.amount" placeholder="请输入金额" type = 'number'/>
        </el-form-item>

        <el-form-item label="图片" prop="img">
          <el-upload
              class="avatar-uploader"
              :action="uploadImgServer"
              accept="jpg,jpeg,png"
              :headers="{
              token: token
            }"
              :show-file-list="false"
              :before-upload="handleBeforeUpload"
              :on-success="handleUrlSuccess"
          >
            <img style="width: 100px; height: 100px; border: 1px solid #e9e9e9;" v-if="form.img" :src="form.img" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog :title="title" v-model="openRefundOrder" width="600px" append-to-body>
      <el-form ref="openRefundOrderRef" :model="searchParams" label-width="100px">

        <el-form-item label="驳回原因" prop="backReasonName">
          <el-input v-model="searchParams.backReasonName" placeholder="请输入原因"  />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="operateBalance">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

  </div>
</template>

<script setup name="MerchantBalance">
import { listMerchantBalance, getMerchantBalance, delMerchantBalance, addMerchantBalance,
  updateMerchantBalance, rechargeList, balanceOperate } from "@/api/business/merchantBalance";
import { getAllMerchantRechargeBalance, getMyMerchantRechargeBalance } from "@/api/business/merchantCapital";
import { allListMerchantInfo } from "@/api/business/merchant";
import { getIsAdmin } from "@/api/system/user";
import { getIsManage } from "@/api/system/user";
import { localGet, uploadImgServer, hasEmoji } from "@/api/business/goodsInfo";

const { proxy } = getCurrentInstance();

const merchantBalanceList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const rechargeBalancePrice = ref(0);
const myBalancePrice = ref(0);
const merchantArr = ref([]);//商户list
const openRefundOrder = ref(false);

const isAdmin = ref(true);//是单条还是多条

const data = reactive({

  uploadImgServer,
  token: localGet('token') || '',

  form: {
    merchantName: null,
    merchantId: null,
    amount:null,
    img:null
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    merchantName: null,
    merchantId: null,
    state : null
  },
  rules: {
    img: [{ required: true, message: "图片必传", trigger: "blur" }],
  },

  searchParams: {
    id: null,
    orderNo: null,
    menuCode: null,
    backReasonName: null,
  },
});

const { queryParams, form, rules, searchParams } = toRefs(data);

const stateOptions = ref([
  {
    value: '',
    label: '全部'
  },{
    value: 0,
    label: '待审核'
  },{
    value: 1,
    label: '审核通过'
  },{
    value: 2,
    label: '审核驳回'
  }
]);


/** 查询商户的余额记录列表 */
function getList() {
  loading.value = true;
  rechargeList(queryParams.value).then(response => {
    merchantBalanceList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });

  getAllMerchantRechargeInfo();
}

// 取消按钮
function cancel() {
  open.value = false;
  openRefundOrder.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    merchantId: null,
    merchantName: null,
    amount: null,
    img: null
  };
  proxy.resetForm("merchantBalanceRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
  getAllMerchantRechargeInfo();

  //查询被搜索商户总充值金额
  getMyMerchantRechargeInfo(queryParams.value.merchantId);
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加商户的余额记录";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getMerchantBalance(_id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改商户的余额记录";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["merchantBalanceRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateMerchantBalance(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addMerchantBalance(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除商户的余额记录编号为"' + _ids + '"的数据项？').then(function() {
    return delMerchantBalance(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('business/admin/merchantBalance/rechargeExport', {
    ...queryParams.value
  }, `充值记录_${new Date().getTime()}.xlsx`)
}

function getAllMerchantRechargeInfo() {
  getAllMerchantRechargeBalance().then(response => {
    rechargeBalancePrice.value = response.data;

  });
}

function getMyMerchantRechargeInfo() {

  if(queryParams.value.merchantId == null){
    queryParams.value.merchantId = 0;
  }

  getMyMerchantRechargeBalance(queryParams.value.merchantId).then(response => {
    myBalancePrice.value = response.data;
  });
}


/** 查询商户信息列表 */
function getMerchantList() {
  allListMerchantInfo().then(response => {
    merchantArr.value = response.rows;
  });
}

function brandChange(name){
  console.log(name)
  console.log(merchantArr)
  for (let i = 0; i < merchantArr.value.length; i++) {
    if (merchantArr.value[i].account === name) {
      form.value.merchantName = name;
      form.value.merchantId = merchantArr.value[i].id;
    }
  }
}

function merchantChange(name){
  for (let i = 0; i < merchantArr.value.length; i++) {
    if (merchantArr.value[i].account === name) {
      queryParams.value.merchantName = name;
      queryParams.value.merchantId = merchantArr.value[i].id;
    }
  }
}


/** 获取是单条还是多条 */
function getUserRole() {
  // getIsAdmin().then(response => {
  //   console.log("---------" , response)
  //   isAdmin.value = response;
  // });

  getIsManage().then(response => {
    console.log("---------" , response)
    isAdmin.value = response;
  });
}


function handleBeforeUpload(file){
  const sufix = file.name.split('.')[1] || ''
  if (!['jpg', 'jpeg', 'png'].includes(sufix)) {
    ElMessage.error('请上传 jpg、jpeg、png 格式的图片')
    return false
  }
}
function handleUrlSuccess (val){
  form.value.img = val.url || ''
}

function handleConfig(id, menuCode) {
  searchParams.value.id = id;
  searchParams.value.menuCode = menuCode;
  proxy.$modal.confirm('是否确认？').then(function () {
    return balanceOperate(searchParams.value);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("操作成功");
  }).catch(() => { });

}


/** 弹窗订单操作 */
function handleOperate( id,  menuCode) {

  searchParams.value.id = id;
  searchParams.value.menuCode = menuCode;
  openRefundOrder.value = true;
  title.value = "操作";
}

/** 弹窗后操作 */
function operateBalance() {

  proxy.$modal.confirm('是否确认？').then(function () {
    return balanceOperate(searchParams.value);
  }).then(() => {
    getList();
    openRefundOrder.value = false;
    proxy.$modal.msgSuccess("操作成功");
  }).catch(() => { });

}


getList();
getAllMerchantRechargeInfo();
getMyMerchantRechargeInfo();
getMerchantList();// 获取所有商户
getUserRole();
</script>


<style scoped>
.add {
  display: flex;
}
.add-container {
  flex: 1;
  height: 100%;
}
.avatar-uploader {
  width: 100px;
  height: 100px;
  color: #ddd;
  font-size: 30px;
}
.avatar-uploader-icon {
  display: block;
  width: 100%;
  height: 100%;
  border: 1px solid #e9e9e9;
  padding: 32px 17px;
}
.el-image-viewer_wrapper{
  z-index: 20028 !important;
}
</style>